<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportUser">excel导出</el-button>
          <el-button type="primary" size="small" @click="openwindow">新增员工</el-button>
        </template>
      </page-tools>
      <!-- v-if="haspermission("import")" -->
      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table border :data="listdate">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img v-imerror="'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fb912bf96dc19b3b23530ae2259b60eb6cf70083f6680b-H9l0ri_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1671674867&t=2f8ea0d44e80809a8b7986ecdd11fc2c'" class="staff" :src="row.staffPhoto||nullImage">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="ofrmatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">{{ formatime(row.timeOfEntry) }}</template>
            <!-- <template #default="{row}">{{ row }}</template> -->
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="openassign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delapi(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="form.page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="form.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!-- 弹窗 -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 权限的弹窗 -->
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getemplyees, delgetemplyees } from '@/api/emplyees'
import employesss from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { addEmployee, AssignRole },
  data() {
    return {
      // 获取初始渲染传给接口的参数
      form: {
        page: 1,
        size: 10
      },
      // 存放初始接口返回的数据
      listdate: [],
      // 存放一共有多少条数据
      total: 0,
      // 控制转圈圈的状态
      loading: false,
      // 控制弹窗(添加)
      showDialog: false,
      // 控制弹窗(分配权限)
      showRoleDialog: false,
      userId: '',
      // 图片为空的地址
      nullImage: 'http://heimamianjing-1315206099.cos.ap-beijing.myqcloud.com/1669080961265%E8%87%AD%E5%AE%9D.jpg'
      // 存放六个按钮的权限
      // infordate: this.$store.state.user.infor.roles.points
    }
  },
  created() {
    this.getemplyee()
  },
  methods: {
    // 修改六个按钮的权限是否需要展示
    // haspermission(data) {
    //   return this.infordate.includes(data)
    // },
    // 获取当前页面的初始数据
    async getemplyee() {
      this.loading = true
      const { data } = await getemplyees(this.form)
      // console.log(data)
      this.listdate = data.rows
      this.total = data.total
      this.loading = false
    },
    // 当前多少条数据每页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.form.size = val
      this.getemplyee()
    },
    // 当前是第几页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.form.page = val
      this.getemplyee()
    },
    // 计算一下序号的排序
    indexMethod(index) {
      return (this.form.page - 1) * this.form.size + index + 1
    },
    // table组件的内置方法 通过判断id看看聘用形式，引入枚举
    ofrmatter(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      const res = employesss.hireType.find(item => item.id === cellValue)
      // console.log(res)
      return res ? res.value : '未知的'
    },
    // 格式化时间
    formatime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 点击删除进行渲染
    delapi(row) {
      // console.log(row)
      this.$confirm('你确认要进行删除么?', '温馨提示').then(async() => {
        // 删除操作成功
        console.log(row)
        await delgetemplyees(row.id)
        this.$message.success('删除操作成功')
        if (this.listdate.length === 1 && this.form.page > 1) {
          this.form.page--
        }
        this.getemplyee()
        // 添加提示
      }).catch(error => {
        console.log(error)
      })
    },
    // 弹窗打开
    openwindow() {
      this.showDialog = true
    },
    // 导出的方法
    async  exportUser() {
      this.form.size = this.total
      const { data: { rows }} = await getemplyees(this.form)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = this.twolist(rows, headersArr, headersRelations)
      console.log(data)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 建立二维数组
    twolist(rows, headersArr, headersRelations) {
      const arr = []
      rows.forEach(element => {
        const list = []
        headersArr.forEach(item => {
          const a = headersRelations[item]
          let b = element[a]
          if (a === 'formOfEmployment') {
            const fig = employesss.hireType.find(val => {
              return val.id === b
            })
            b = fig ? fig.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(a)) {
            b = this.formatime(element[a])
          }

          list.push(b)
        })
        arr.push(list)
      })
      return arr
    },
    // 打开权限的弹窗
    openassign(id) {
      this.showRoleDialog = true
      this.userId = id
      // console.log(this.userId)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
    .staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
  }
</style>
